package com.atguigu.gulimall.member.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class MyFeignConfig {

    /**
     * 解决Feign远程调用时，丢失请求头信息的问题
     * fegin在远程调用前，会调用所有RequestInterceptor拦截器的apply()方法。
     * 所以，只需向容器中注入一个RequestInterceptor实例，并在apply()方法中，重新添加请求头信息即可。
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //1、通过RequestContextHolder拿到旧的request请求（RequestContextHolder本质上是通过ThreadLocal获取的request数据，所以异步情况下会有问题）
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null) {
                    HttpServletRequest request = attributes.getRequest();
                    if (request != null) {
                        //2、获取旧request请求头中的cookie信息
                        String cookie = request.getHeader("Cookie");
                        //3、同步cookie信息到feign构建的新请求中
                        requestTemplate.header("Cookie", cookie);
                    }
                }
            }
        };
    }


}
